<?php
/*
 * class shmop
 * Use for communication with c, read shared memeory.
 * Create at: 14:01 2012/10/31
 * Author: leixun(lein_urg@163.com)
 * version 1 - 14:01 2012/10/31
 */

class shmop{
	private $read_start = 0;
	private $write_start = 0;
	
	private $max = 0;	
	private $start = 0;
	
	private $size = 1024;
	public function shmop($start, $max, $size)
	{
		$this->start = $start;
		$this->read_start = $start;
		$this->write_start = $start;
		$this->max = start + $max;
		
		if($size) $this->size = $size;
	}
	
	/**
	 * write data to shared memory
	 * @param $id data to save
	 */
	public function auto_write($data)
	{
		if($size<strlen($data)) $size = strlen($data);

		$this->write_start ++;
		if($this->write_start > $this->max) $this->write_start = $this->start;
		$id = $this->write_start;


		$shmid = shmop_open($id, 'c', 0666, $this->size);
		if(shmop_size($shmid)>0) return false;

		$return = shmop_write($shmid, $data);
		shmop_close($shmid);
		return $return;
	}
	
	/**
	 * read data from shared memory and remove shared memory
	 * 
	 */
	public function auto_read($delete = true)
	{
		$this->read_start ++;
		if($this->read_start > $this->max) $this->read_start = $this->start;
		$id = $this->read_start;

		$shmid = shmop_open($id, 'c', 0666, $this->size);
		if(shmop_size($shmid)<1) return false;

		$return = shmop_read($shmid, 0, shmop_size($shmid));
		if($delete) shmop_delete($shmid);
		shmop_close($shmid);

		return $return;
	}
}